<template>
	<div class="content-box add-good">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
			<div class="el-form-sub-title">商品类型</div>
			<el-form-item class="good-type-form-item" prop="productType">
				<el-radio-group v-model="form.productType" class="good-type">
					<el-radio :value="0" size="large" border>
						<div>
							<p class="text-primary">实物商品</p>
							<p class="text-regular font13">通过物流直接发货</p>
						</div>
					</el-radio>
					<el-radio :value="1" size="large" border>
						<div>
							<p class="text-primary">数字酒藏</p>
							<p class="text-regular font13">生成数字酒藏，提货时核销发货</p>
						</div>
					</el-radio>
				</el-radio-group>
			</el-form-item>
			<div class="el-form-sub-title">货品信息</div>
			<el-form-item label="选择货品" prop="productWarehouseId" :rules="rules.productWarehouseId">
				<RefreshSelect
					v-model="form.productWarehouseId"
					:api="fetchWarehousingList"
					:option-map="{ label: 'label', value: 'id' }"
					popper-class="refresh-select-code"
					:showButton="false"
					@change="onMaterialChange"
					:dataFormat="warehousingListFormat"
					:initChange="(val) => onMaterialChange(val, true)"
					:disabled="!!editId"
				></RefreshSelect>
			</el-form-item>
			<el-form-item label="生产年份" prop="productYear">
				<el-input-number disabled :controls="false" class="num-left mr10" v-model="form.productYear" :min="0" :max="9999" placeholder="自动关联" />年
			</el-form-item>
			<div class="el-form-sub-title">基本信息</div>
			<el-form-item label="商品图片" prop="productImage">
				<uploadImage v-model:file-list="form.productImage" :limit="12" :fileSize="300 / 1024" packageName="product">
					<template #tip> 建议尺寸：800*800像素，300kb以下，第一张为默认首图，最多上传12张，支持PNG/JPG格式 </template>
				</uploadImage>
			</el-form-item>
			<el-form-item label="商品名称" prop="productName">
				<el-input v-model="form.productName" :maxlength="50" placeholder="输入50个字以内的商品名称" />
			</el-form-item>
			<el-form-item label="微信主图视频" prop="videoUrlWx">
				<uploadVideo v-model:file-list="form.videoUrlWx" :fileSize="30" packageName="product">
					<template #tip> 视频大小不超过 30 MB，建议时长1分钟以内， 建议宽高比1：1或16:9， 视频文件格式建议：.mp4</template>
				</uploadVideo>
			</el-form-item>
			<el-form-item label="支付宝主图视频" prop="videoUrlAlipay">
				<el-input v-model="form.videoUrlAlipay" placeholder="输入优酷视频链接" />
				<div class="el-upload__tip" style="width: 100%">
					<p>
						Step1.请使用小程序关联<a href="https://mp.youku.com/new/video" target="_block"
							><el-button style="vertical-align: baseline" link type="primary" size="small" @click="">支付宝优酷账号上传视频</el-button></a
						>并获得视频码
					</p>
					<p>Step2.复制并将视频码链接进行输入(示例：XNjM4MTk0NTkyMA==)</p>
				</div>
			</el-form-item>
			<el-form-item label="视频封面" prop="videoImage">
				<uploadImage v-model:file-list="form.videoImage" packageName="product" :fileSize="300 / 1024">
					<template #tip> 建议尺寸：800*800像素，300kb以下，支持PNG/JPG格式 </template>
				</uploadImage>
			</el-form-item>
			<!-- <el-form-item label="商品编码" prop="productCode">
				<el-input v-model="form.productCode" :maxlength="30" placeholder="输入30个字以内的商品编码" />
				<p class="el-upload__tip">商品编码支持数字+字母组合形式，不支持中文，商品编码将在同步支付宝商品库时使用，商品编码具有唯一性不可重复</p>
			</el-form-item> -->
			<el-form-item label="商品分类" prop="productTypeId">
				<RefreshSelect
					v-model="form.productTypeId"
					:api="fetchTypeList"
					:option-map="{ label: 'name', value: 'id' }"
					popper-class="refresh-select-type"
					link="/goods/type"
				></RefreshSelect>
			</el-form-item>
			<el-form-item label="商品简介" prop="productDesc">
				<el-input type="textarea" v-model="form.productDesc" :rows="3" :maxlength="30" placeholder="输入30个字以内的商品简介" />
			</el-form-item>
			<el-form-item label="收藏指数" prop="collection">
				<Rating v-model="form.collection"></Rating>
				<p class="el-upload__tip mt-8">收藏指数根据饮用价值、投资价值、社交价值体系综合所得，请选择合适的收藏指数星级</p>
			</el-form-item>
			<div class="el-form-sub-title">规格库存</div>
			<el-form-item label="商品规格" prop="tag">
				<tagGroup v-model="form.tag" @change="changeTag"></tagGroup>
			</el-form-item>
			<el-form-item label="规格明细" prop="skus">
				<specification ref="specificationRef" :is-edit="!!editId" :material="material" v-model="form" @submit="submit"></specification>
			</el-form-item>
			<div v-if="form.productType == 0">
				<div class="el-form-sub-title">物流信息</div>
				<el-form-item label="配送方式" prop="shippingType">
					<el-checkbox-group v-model="form.shippingType">
						<el-checkbox :label="0" :value="0">快递发货</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="快递运费" prop="shippingPriceType">
					<el-radio-group class="flex-column flex-vstart" v-model="form.shippingPriceType">
						<el-radio :label="0">
							<div class="flex-center w-full">
								统一邮费
								<el-form-item class="ml10" v-if="form.shippingPriceType == 0" labelWidth="0" prop="shippingPrice">
									<el-input
										:formatter="(value:any) => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
										:parser="(value:any) => value.replace(/\¥\s?|(,*)/g, '')"
										v-model="form.shippingPrice"
										style="width: 300px"
									></el-input>
								</el-form-item>
							</div>
						</el-radio>
						<el-radio :label="1" class="mt10">
							<div class="flex-center w-full">
								运费模板
								<el-form-item v-if="form.shippingPriceType == 1" labelWidth="0" class="w-full ml10" prop="shippingCostTemplateId">
									<RefreshSelect
										v-model="form.shippingCostTemplateId"
										:api="fetchFreightList"
										:option-map="{ label: 'name', value: 'id' }"
										popper-class="refresh-select-temp"
										link="/goods/freight"
										style="width: 300px"
									></RefreshSelect>
								</el-form-item>
							</div>
						</el-radio>
					</el-radio-group>
				</el-form-item>
			</div>
			<div v-else class="mb20">
				<div class="el-form-sub-title">酒藏管理</div>
				<el-form-item label="免费仓储" prop="storage">
					<el-input-number class="num-left" :min="0" :max="999999999" :controls="false" v-model="form.storage" placeholder="填写免费仓储年数" />
				</el-form-item>
				<el-form-item label="仓储收费" prop="storagePrice">
					<el-input-number
						class="num-left"
						:min="0"
						:max="999999999"
						:controls="false"
						v-model="form.storagePrice"
						placeholder="填写超出免费仓储后每年收费费用"
					/>
				</el-form-item>
			</div>
			<div class="el-form-sub-title">商品详情</div>
			<el-form-item label="详情图片" prop="productInfoImage">
				<uploadImage v-model:file-list="form.productInfoImage" :fileSize="300 / 1024" :limit="50" :dragSort="true" packageName="product">
					<template #tip>
						建议尺寸：宽度800px，高度自适应，300kb以下，最多上传50张，支持PNG/JPG格式<br />
						<el-divider style="margin: 10px 0"></el-divider>
						上传图片{{ form.productInfoImage.length }}/50，拖拽可调整排序
					</template>
				</uploadImage>
			</el-form-item>
			<div class="el-form-sub-title">高级设置</div>
			<el-form-item label="开售时间" prop="saleType">
				<el-radio-group class="flex-column flex-vstart" v-model="form.saleType">
					<el-radio :label="0"> 立即开售 </el-radio>
					<el-radio :label="1">
						<div class="flex-center w-full">
							定时开售
							<el-form-item prop="saleStartTime" v-if="form.saleType == 1">
								<el-date-picker style="width: 300px" class="ml10" v-model="form.saleStartTime" type="datetime" placeholder="选择开售时间" />
							</el-form-item>
						</div>
					</el-radio>
					<el-radio :label="2"> 放入仓库 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="定时下架" prop="takeDown">
				<el-radio-group class="flex-column flex-vstart" v-model="form.takeDown">
					<el-radio :label="0"> 关闭 </el-radio>
					<el-radio :label="1">
						<div class="flex-center w-full">
							开启
							<el-form-item prop="saleEndTime" v-if="form.takeDown == 1">
								<el-date-picker style="width: 300px" class="ml10" v-model="form.saleEndTime" type="datetime" placeholder="选择下架时间" />
							</el-form-item>
						</div>
					</el-radio>
					<p class="el-upload__tip">开启定时下架后，系统会在设置得时间下架商品，下架时间需要晚于开售时间。</p>
				</el-radio-group>
			</el-form-item>
			<!-- <el-form-item label="商品单位" prop="productUnitId">
				<RefreshSelect
					v-model="form.productUnitId"
					:api="fetchUnitList"
					:option-map="{ label: 'name', value: 'id' }"
					popper-class="refresh-select"
					link="/goods/unit"
				></RefreshSelect>
			</el-form-item> -->
			<el-form-item label="保障服务" prop="productServiceId">
				<el-checkbox-group v-model="form.productServiceId">
					<el-checkbox v-for="item in serviceList" :key="item.id" :label="item.id" :value="item.id">{{ item.name }}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item label="商品参数" prop="productArgumentId">
				<RefreshSelect
					v-model="form.productArgumentId"
					:api="fetchArgumentList"
					:option-map="{ label: 'name', value: 'id' }"
					popper-class="refresh-select-arg"
					link="/goods/argument"
					@change="getArgumentDetail"
				></RefreshSelect>
			</el-form-item>
			<el-form-item>
				<el-table class="form-table w-full" :data="paramsData">
					<el-table-column prop="name" label="参数名称" width="120" />
					<el-table-column prop="value" label="参数值" min-width="260" />
				</el-table>
			</el-form-item>
			<el-form-item label="商品排序" prop="orderIdx">
				<el-input-number
					:controls="false"
					class="num-left"
					v-model="form.orderIdx"
					@blur="
						() => {
							form.orderIdx = form.orderIdx || 0;
						}
					"
					:min="0"
					:max="999999999"
					placeholder="输入商品排序"
				/>
			</el-form-item>
			<el-form-item label="起始销量" prop="initSalesNum">
				<el-input-number :controls="false" class="num-left" v-model="form.initSalesNum" :min="0" placeholder="输入起始销量" />
			</el-form-item>
			<el-form-item label="隐藏显示" prop="hide">
				<el-radio-group v-model="form.hide" class="w-full">
					<el-radio :value="0"> 否 </el-radio>
					<el-radio :value="1"> 是 </el-radio>
				</el-radio-group>
				<p class="el-upload__tip mt0">商品设为隐藏显示后将不在小程序端直接展示，但依然可以通过链接访问</p>
			</el-form-item>
			<el-form-item label="商品推荐" prop="recommended">
				<el-radio-group v-model="form.recommended" class="w-full">
					<el-radio :value="0"> 否 </el-radio>
					<el-radio :value="1"> 是 </el-radio>
				</el-radio-group>
				<p class="el-upload__tip mt0">商品设为推荐将在首页、商城、支付成功页等页面进行推广展示</p>
			</el-form-item>
			<el-form-item label="商品限购" prop="productLimit">
				<el-radio-group v-model="form.productLimit" class="w-full">
					<el-radio :value="0"> 否 </el-radio>
					<el-radio :value="1"> 是 </el-radio>
				</el-radio-group>
				<p class="el-upload__tip mt0">限制用户单次可购买数量</p>
			</el-form-item>
			<div class="flex-center mb18" v-if="form.productLimit == 1">
				<el-form-item label="个人限购" prop="productUserLimitNum" class="mb0">
					<el-input-number :controls="false" class="num-left" v-model="form.productUserLimitNum" :min="1" placeholder="输入限购数量" />
				</el-form-item>
				<el-form-item label="经销商限购" prop="productDealerLimitNum">
					<el-input-number :controls="false" class="num-left" v-model="form.productDealerLimitNum" :min="1" placeholder="输入限购数量" />
				</el-form-item>
			</div>
			<el-form-item label="用户限购" prop="userLimit">
				<el-radio-group v-model="form.userLimit" class="w-full">
					<el-radio :value="0"> 否 </el-radio>
					<el-radio :value="1"> 是 </el-radio>
				</el-radio-group>
				<p class="el-upload__tip mt0">限制用户总共可购买次数</p>
			</el-form-item>
			<div class="flex-center mb18" v-if="form.userLimit == 1">
				<el-form-item label="个人限购" prop="userLimitNum" class="mb0">
					<el-input-number :controls="false" class="num-left" v-model="form.userLimitNum" :min="1" placeholder="输入限购次数" />
				</el-form-item>
				<el-form-item label="经销商限购" prop="dealerLimitNum">
					<el-input-number :controls="false" class="num-left" v-model="form.dealerLimitNum" :min="1" placeholder="输入限购次数" />
				</el-form-item>
			</div>
			<!-- <el-form-item label="推广插件" prop="plugin">
				<el-radio-group v-model="form.plugin" class="w-full">
					<el-radio :value="0"> 否 </el-radio>
					<el-radio :value="1"> 是 </el-radio>
				</el-radio-group>
				<p class="el-upload__tip mt0">推广插件将用于支付宝公域会场进行推广时使用</p>
			</el-form-item> -->
			<el-form-item label-width="0">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="onSubmit">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="tsx" name="addGood">
import { ref, reactive, onMounted } from 'vue';
import { type FormRules, ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import uploadImage from '/@/components/upload/image.vue';
import uploadVideo from '/@/components/upload/video.vue';
import tagGroup from '/@/components/tagGroup/index.vue';
import specification from './compontents/specification.vue';
import RefreshSelect from '/@/components/refreshSelect/index.vue';
import Rating from '/@/components/rating/index.vue';
import {
	fetchGoodDetail,
	fetchTypeList,
	fetchServiceList,
	fetchCreateGood,
	fetchUpdateGood,
	fetchArgumentList,
	fetchFreightList,
	fetchWarehousingList,
	fetchArgumentDetail,
} from '/@/api/goods';
import { useRoute, useRouter } from 'vue-router';
import { fenToYuan } from '/@/utils/commonFunction';
const route = useRoute();
const router = useRouter();

const formRef = ref();
const form = ref<any>({
	orderIdx: 0,
	productType: 0,
	shippingType: [0],
	tag: [],
	skus: [],
	videoUrlWx: [],
	videoImage: [],
	productImage: [],
	productInfoImage: [],
	productServiceId: [],
	saleStartTime: '',
	saleEndTime: '',
	collection: 0,
	hide: 0,
	productLimit: 0,
	userLimit: 0,
	recommended: 0,
	plugin: 0,
	takeDown: 0,
	saleType: 0,
	shippingPriceType: 0,
	shippingPrice: 0,
});

const specificationRef = ref();
const serviceList = ref([]);

const editId = ref<any>('');

const paramsData = ref([]);

const material = ref();

// const validateSkus = (rule: any, value: any, callback: any) => {
// 	if (value.length == 0) {
// 		callback(new Error('规格明细不能为空'));
// 	} else {
// 		callback();
// 	}
// };

//校验规则
const rules = reactive<FormRules<any>>({
	productImage: [{ required: true, trigger: 'blur', message: '商品图片不能为空' }],
	productName: [{ required: true, trigger: 'blur', message: '商品名称不能为空' }],
	productWarehouseId: [{ required: true, trigger: 'blur', message: '物料编码不能为空' }],
	productTypeId: [{ required: true, message: '请选择商品分类', trigger: ['change', 'blur'] }],
	productYear: [{ required: true, message: '生产年份不能为空', trigger: ['change', 'blur'] }],
	collection: [{ required: true, message: '请选择收藏指数', trigger: ['change', 'blur'] }],
	tag: [{ required: true, message: '商品规格不能为空', trigger: ['change', 'blur'] }],
	skus: [{ required: true, message: '规格明细不能为空', trigger: ['change', 'blur'] }],
	shippingType: [{ required: true, message: '配送方式不能为空', trigger: ['change', 'blur'] }],
	shippingPrice: [{ required: true, message: '统一运费不能为空', trigger: ['change', 'blur'] }],
	shippingCostTemplateId: [{ required: true, message: '运费模板不能为空', trigger: ['change', 'blur'] }],
	saleType: [{ required: true, message: '请选择开售时间', trigger: ['change', 'blur'] }],
	saleStartTime: [{ required: true, message: '开售时间不能为空', trigger: ['change', 'blur'] }],
	takeDown: [{ required: true, message: '定时下架不能为空', trigger: ['change', 'blur'] }],
	saleEndTime: [{ required: true, message: '下架时间不能为空', trigger: ['change', 'blur'] }],
	productUnitId: [{ required: true, message: '请选择商品单位', trigger: ['change', 'blur'] }],
	storage: [{ required: true, message: '免费仓储年数不能为空', trigger: ['change', 'blur'] }],
	storagePrice: [{ required: true, message: '仓储收费不能为空', trigger: ['change', 'blur'] }],
	productUserLimitNum: [{ required: true, message: '个人限购不能为空', trigger: ['change', 'blur'] }],
	productDealerLimitNum: [{ required: true, message: '经销商限购不能为空', trigger: ['change', 'blur'] }],
	userLimitNum: [{ required: true, message: '个人限购不能为空', trigger: ['change', 'blur'] }],
	dealerLimitNum: [{ required: true, message: '经销商限购不能为空', trigger: ['change', 'blur'] }],
});

const back = () => {
	router.push('/goods/list');
};

const changeTag = (data: any) => {
	const skus: any = data.value.map((v: any) => {
		const sku = form.value.skus.find((item: any) => item.skuName === v) || {};
		return {
			skuName: v,
			recommendedPrice: material.value ? material.value.recommendedPrice : undefined,
			costPrice: material.value ? material.value.costPrice : undefined,
			...sku,
		};
	});
	form.value.skus = skus;
};

const warehousingListFormat = (data: any) => {
	return data.map((item: any) => {
		return {
			...item,
			label: `【${item.id}】${item.materialCode}，${item.materialName}`,
		};
	});
};

const onMaterialChange = (value: any, init?: boolean) => {
	material.value = {
		...value,
		recommendedPrice: fenToYuan(value.recommendedPrice),
		costPrice: fenToYuan(value.costPrice),
	};
	if (!init) {
		form.value.materialUnit = '';
	}
	form.value.productWarehouseId = value.id;
	form.value.productYear = value.productYear;
	form.value.skus = form.value.skus.map((item: any) => {
		item.recommendedPrice = fenToYuan(value.recommendedPrice);
		item.costPrice = fenToYuan(value.costPrice);
		return item;
	});
};

const getArgumentDetail = async (value: any) => {
	const res = await fetchArgumentDetail({ id: value.id });
	if (res.code === 200) {
		paramsData.value = res.data.details;
	}
};

const onSubmit = async () => {
	specificationRef.value.handleSubmit();
};

const submit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params: any = {
				...form.value,
			};
			params.saleStartTime = params.saleType == 1 ? dayjs(params.saleStartTime).format('YYYY-MM-DD HH:mm:ss') : undefined;
			params.saleEndTime = params.takeDown == 1 ? dayjs(params.saleEndTime).format('YYYY-MM-DD HH:mm:ss') : null;
			params.productImage = params.productImage?.map((item: any) => item.url).join(',');
			params.productInfoImage = params.productInfoImage?.map((item: any) => item.url).join(',');
			params.videoUrlWx = params.videoUrlWx?.map((item: any) => item.url).join(',');
			params.videoImage = params.videoImage?.map((item: any) => item.url).join(',');
			params.productServiceId = params.productServiceId ? params.productServiceId.join(',') : '';
			params.shippingType = params.shippingType ? params.shippingType.join(',') : '';
			params.skus = params.skus?.map((item: any) => {
				return {
					...item,
					originalPrice: item.originalPrice * 100,
					presentPrice: item.presentPrice * 100,
					recommendedPrice: item.recommendedPrice * 100,
					costPrice: item.costPrice * 100,
					productAmount: 1,
					skuImage: item.skuImage ? item.skuImage.map((item: any) => item.url).join(',') : '',
				};
			});
			params.storagePrice = params.storagePrice * 100;
			params.shippingPrice = params.shippingPrice * 100;
			const res = editId.value ? await fetchUpdateGood(params) : await fetchCreateGood(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑商品成功' : '新增商品成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const formatData = (data: any) => {
	return {
		...data,
		orderIdx: data.orderIdx || 0,
		productImage: data.productImage ? data.productImage.split(',').map((url: any) => ({ url })) : [],
		productInfoImage: data.productInfoImage ? data.productInfoImage.split(',').map((url: any) => ({ url })) : [],
		videoUrlWx: data.videoUrlWx ? data.videoUrlWx.split(',').map((url: any) => ({ url })) : [],
		videoImage: data.videoImage ? data.videoImage.split(',').map((url: any) => ({ url })) : [],
		productTypeId: data.productTypeObject?.id,
		productUnitId: data.productUnit?.id,
		tag: data.skus ? data.skus.map((v: any) => v.skuName) : [],
		productWarehouseId: data.productWarehouseId || '',
		skus: data.skus
			? data.skus.map((v: any) => {
					return {
						...v,
						originalPrice: fenToYuan(v.originalPrice),
						presentPrice: fenToYuan(v.presentPrice),
						recommendedPrice: fenToYuan(v.recommendedPrice),
						costPrice: fenToYuan(v.costPrice),
						skuImage: v.skuImage ? v.skuImage.split(',').map((url: any) => ({ url })) : [],
					};
				})
			: [],
		shippingType: [0],
		productServiceId: data.productService ? data.productService.map((v: any) => v.id) : [],
		hide: data.hide ? 1 : 0,
		recommended: data.recommended ? 1 : 0,
		productLimit: data.productLimit ? 1 : 0,
		userLimit: data.userLimit ? 1 : 0,
		plugin: data.plugin ? 1 : 0,
		takeDown: data.saleEndTime == null ? 0 : 1,
		shippingCostTemplateId: data.shippingCostTemplate?.id,
		productArgumentId: data.productArgument?.id,
		storagePrice: fenToYuan(data.storagePrice),
		shippingPrice: fenToYuan(data.shippingPrice),
	};
};

onMounted(async () => {
	const { name, params, query } = route;
	const id = params?.id || query?.id;

	if (id) {
		const res = await fetchGoodDetail({ id });
		if (res.code === 200) {
			const data = formatData(res.data.product);
			if (name == 'addGood') {
				form.value = {
					...data,
					id: '',
				};
				material.value = {
					materialCode: data.materialCode,
					materialUnit: data.materialUnit,
				};
				paramsData.value = data.productArgument?.details || [];
			} else {
				form.value = data;
				paramsData.value = data.productArgument?.details || [];
				editId.value = id;
			}
		}
	}

	// 获取保障服务列表
	const res = await fetchServiceList({ page: 1, pageSize: 1000 });
	if (res.code == 200) {
		serviceList.value = res.data.records;
	}
});
</script>

<style scoped lang="scss">
.add-good {
	.good-type-form-item {
		.el-form-item__content {
			margin-left: 0;
		}
	}
	.good-type {
		.el-radio {
			height: max-content;
			padding: 10px;
			min-width: 240px;
			p {
				line-height: 24px;
			}
		}
	}
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number,
		.refresh-select-wrapper {
			width: 100%;
			max-width: 450px;
		}
	}
}
</style>
<style lang="scss">
.add-good {
	.good-type-form-item {
		.el-form-item__content {
			margin-left: 0 !important;
		}
	}
}
</style>
